package nc2grd;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class NC2Grd implements HandleNC {

	String str_ncSource;  // 各时间尺度 NC数据所在根目录
	String str_NCL;       // NCL 脚本模板文件
	String str_NCLExec;   // NCL 脚本执行文件
	
	public NC2Grd(String strDirOfNCEP, String strPathOfNCLTemplate){
		str_ncSource = strDirOfNCEP;
		str_NCL = strPathOfNCLTemplate;
		str_NCLExec = "";
	}
	
	public ArrayList<String> GetGrd(String sElem, String sScale ,String sKind){
		// sElem: air uwnd vwnd sst hgt .... ...
		// sScale: daily monthly
		
		String str_ncPath = str_ncSource + sScale +"/"+sKind+"/"+ sElem+"/";
		
		
		replaceNCL(sElem,str_ncPath);  //替换NCL模板
		
		String strCMD = "ncl " + str_NCLExec;
		ArrayList<String> grdList = new ArrayList<String>();
		int res;
        try{
			res = executeExe(strCMD);  // 执行NCL数据转换脚本
        }catch (InterruptedException e){
        	e.printStackTrace();
        }
	
		// 返回文件列表
        GrdFilter Filter = new GrdFilter();
        File myDir = new File(str_ncPath);
        File[] dirs = myDir.listFiles(Filter);
        for(File fp:dirs){
        	grdList.add(fp.getAbsolutePath());
        }
        return grdList;
		//return null;
	}
	
	// 替换NCL模板，生成可执行NCL文件
	private void replaceNCL(String sElem,String str_ncPath){
		List<String> lstNCLTemplate = null;
		
		str_NCLExec = str_ncPath + sElem + ".ncl";
		File fNCLRaw = new File(str_NCL);
		File fNCLExec = new File(str_NCLExec);
		try {
			lstNCLTemplate = (List<String>)FileUtils.readLines(fNCLRaw, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		StringBuilder strBuilder = new StringBuilder();
		for(String sTemp:lstNCLTemplate){
			sTemp = sTemp.replace("{VAR}", sElem) + "\n";
			sTemp = sTemp.replace("{nclPath}",str_ncPath);
			strBuilder.append(sTemp);
		}
		
		try{
			FileUtils.writeStringToFile(fNCLExec, strBuilder.toString());
			}catch(IOException e){
			e.printStackTrace();
		}
		
	}
	
	// 执行NCL脚本
	private int executeExe(String exeName) throws InterruptedException{
		Runtime runTime=Runtime.getRuntime();
		int res = 0;
		BufferedReader in = null;
		try {
			Process process=runTime.exec(exeName);
			String str ="";
			in = new BufferedReader(new InputStreamReader(process.getInputStream()));  
			while ((str = in.readLine())!= null) {  
			
			}  
			in.close();
			res = process.waitFor();
			System.out.println("NCL的返回值是："+res);
			process.destroy();
		} catch (IOException e) {
			System.out.println("调用Exe出错！！！");
			e.printStackTrace();
		} finally{
			try {
				if(null!=in){
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return res;
	}
	
	public static void main(String[] Argc) {
		/*if(Argc.length < 2){
			System.out.println("Usage: *.exe  rootdir4NC  dir4NCLTemplate");
			System.out.println("rootdir4NC,i.e. /gpfs/home/css/liuxs/ftp/download/");
			System.out.println("dir4NCLTemplate,i.e. /gpfs/home/css/liuxs/NC2Grd/nc2grd.ncl");
			return;
		}//*/
		
		//NC2Grd testT = new NC2Grd(Argc[0],Argc[1]);
		// NC2Grd testT = new NC2Grd("/gpfs/home/css/liuxs/ftp/download/","/gpfs/home/css/liuxs/NC2Grd/nc2grd.ncl");
		// ArrayList<String> t = testT.GetGrd("air", "daily");
		// for(String s: t){
		    // System.out.println(s);
		// }
	}
}
